﻿using System;
using System.Collections.Generic;
using System.Text;
using Animals.Model;
using System.Xml.Serialization;
using System.IO;
using Dogs.Model;

namespace Dogs.Business
{
    static class Serializator
    {
        public const string ANIMALS_FILE_PATH = DATA_FOLDER_PATH + "/animals.xml";
        public const string PARENTS_FILE_PATH = DATA_FOLDER_PATH + "/parents.xml";
        public const string DATA_FOLDER_PATH = "data";

        static Serializator()
        {
            if (!Directory.Exists(DATA_FOLDER_PATH))
            {
                Directory.CreateDirectory(DATA_FOLDER_PATH);
            }
        }

        public static void CreateAnimals(List<Animal> animals)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(List<Animal>));
            TextWriter textWriter = new StreamWriter(@ANIMALS_FILE_PATH);
            serializer.Serialize(textWriter, animals);
            textWriter.Close();
        }

        public static void CreateParents(List<ParentsPair> parents)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(List<ParentsPair>));
            TextWriter textWriter = new StreamWriter(@PARENTS_FILE_PATH);
            serializer.Serialize(textWriter, parents);
            textWriter.Close();
        }

        public static List<Animal> GetAllAnimals()
        {
            if (File.Exists(ANIMALS_FILE_PATH))
            {
                XmlSerializer deserializer = new XmlSerializer(typeof(List<Animal>));
                TextReader textReader = new StreamReader(@ANIMALS_FILE_PATH);
                List<Animal> animals;
                animals = (List<Animal>)deserializer.Deserialize(textReader);
                textReader.Close();

                return animals;
            }

            return null;
        }

        public static List<ParentsPair> GetAllParents()
        {
            if (File.Exists(PARENTS_FILE_PATH))
            {
                XmlSerializer deserializer = new XmlSerializer(typeof(List<ParentsPair>));
                TextReader textReader = new StreamReader(@PARENTS_FILE_PATH);
                List<ParentsPair> parents;
                parents = (List<ParentsPair>)deserializer.Deserialize(textReader);
                textReader.Close();

                return parents;
            }
            return null;
        }
    }
}
